$(function () {
    checkLoad();
    $(document).scroll(checkLoad);
    $(".list-group").click(function (e) {
        var target = $(e.target);
        var id = $(target).attr("data-id");
        if (target.is(":not(.liked)>.oi-thumb-up")) {
            $.post("/like", {
                id: id
            }, function (data) {
                if (data.status){
                    var liked = $.cookie("liked");
                    if(liked===undefined){
                        liked = id;
                    }else {
                        liked += (","+id);
                    }
                    $.cookie("liked", liked);
                }
            });

            var parent = target.parent();
            parent.addClass("liked");
            var likeNum = " "+(parseInt(parent.text())+1);
            target.text("");
            var children = target.detach("*");

            parent.text(likeNum);
            parent.prepend(children);
            target.tooltip({
                title: "感谢点赞！",
                trigger: "manual"
            }).tooltip("show");
            setTimeout(function () {
                $(e.target).tooltip("hide");
            }, 1000);
        }
    });
});

function checkLoad(){
    var spinner = $("#load-spinner");
    var currPage = spinner.attr("data-current-page");
    if (spinner.is(":in-viewport")&&currPage>=0&&!spinner.hasClass("on-load")) {
        spinner.addClass("on-load");
        loadMore(currPage - 1);
        spinner.attr("data-current-page", currPage-1);
    }
}

function loadMore(page) {
    $.post("", {page: page}, function (data) {
        var commentList = $("#comment-list");
        if (data.length>0) {
            data.reverse();
            var likedList = $.cookie("liked")? $.cookie("liked").split(","):[];
            data.forEach(function (el) {
                commentList.append(getCommentTemplate(el.id, el.nickName, el.comment, el.dateTime, el.likeNum, likedList.includes(el.id.toString())));
            });
            $("#load-spinner").removeClass("on-load");
        }else {
            $("#load-spinner").hide();
        }
    }, "json");
}

function submitComment() {
    var submitBtn = $("#submit-btn");
    submitBtn.prop("disabled", true);
    var form = $("#comment-form");
    $.post("submit", form.serialize(), function (data) {
        if (data.status){
            var commentList = $("#comment-list");
            commentList.prepend(getCommentTemplate(
                data.msg,
                $("#nick-name").val(),
                $("#comment-content").val(),
                Date(),
                0,
                false,
                true
            ));
            form[0].reset()
        } else {
            alert("发送失败！");
        }
        submitBtn.prop("disabled", false);
    });
}

function del(el) {
    var parent = $(el).parent().parent().parent().parent();
    var id = parent.find('.comment-like>span').attr('data-id');
    $.post("/del", {
        id: id
    }, function (data) {
        if (data.status){
            parent.remove();
        }else {
            alert('删除失败！');
        }
    });
}

function login() {
    $.post("/login", {
        username: $("#admin-username").val(),
        password: $("#admin-password").val()
    }, function (data) {
        if (data.status){
            history.go(0)
        }else {
            alert(data.msg);
        }
    });
}

function logoff() {
    $.post("/logoff", null, function (data) {
        if (data.status){
            history.go(0)
        }else {
            alert(data.msg);
        }
    });
}

function getCommentTemplate(id, nickName, comment, dateTime, likeNum, isLiked, isSelf) {
    return "<li class=\"list-group-item list-group-item-action flex-column align-items-start\">\n" +
        "<div class=\"d-flex w-100 justify-content-between\">\n" +
        "<h5 class=\"mb-1\">"+ nickName.replace(/\n/g, "<br/>")+"</h5>\n" +
        "<div>\n" +
        (isSelf||$(".admin-btn").length === 0?"<small class=\"comment-del\"><a href=\"javascript:void(0)\" onclick=\"del(this)\">删除</a></small>":"") +
        "<small class=\"comment-like"+(isLiked?" liked": "") +"\"><span class=\"oi oi-thumb-up\" data-id=\""+id+"\"></span> "+likeNum+"</small>\n" +
        "<small class=\"comment-id\">#"+id+"</small>\n" +
        "</div>" +
        "</div>\n" +
        "<small>"+formatDate(dateTime)+"</small>\n" +
        "<p class=\"mb-1\">"+ comment.replace(/\n/g, "<br/>") +"</p>\n" +
        "</li>";
}

function formatDate(str) {
    var pattern_1 = /^(\d{4}-\d{2}-\d{2})T(\d{2}:\d{2}:\d{2})\.000\+0000$/m;

    if (pattern_1.test(str)){
        var result = str.match(pattern_1);
        return result[1]+" "+result[2];
    } else {
        var date = new Date();
        return date.getFullYear() + "-" +
            prefixInteger(date.getMonth()+1, 2) + "-" +
            prefixInteger(date.getDate(), 2) + " " +
            prefixInteger(date.getHours(), 2) + ":" +
            prefixInteger(date.getMinutes(), 2) + ":" +
            prefixInteger(date.getSeconds(), 2)
    }
    
}

function prefixInteger(num, n) {
    return (Array(n).join('0') + num).slice(-n);
}